<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/3/15
 * Time: 下午3:01
 */

namespace App\Sock\Parser;

use App\Sock\Controller\Device;

use EasySwoole\Core\Socket\AbstractInterface\ParserInterface;
use EasySwoole\Core\Socket\Common\CommandBean;


class Tcp implements ParserInterface
{

    /*
     * 假定，客户端与服务端都是明文传输。控制格式为 serviceName:actionName:args
     */
    public static function decode($raw, $client)
    {
        var_dump($raw);
        $format = 'Chead/Ctype/ndevice/ndata/Ccheck/Ctail';
        $data = unpack($format, $raw);

        // 对于非定长数据，如何处理？
        // 是否会有连续多个数据同时到达？

        $bean = new CommandBean();
        if (!$data) {
            $bean->setControllerClass(\App\Sock\Controller\Tcp::class);
            $bean->setAction('error');
            $bean->setArg('data', $raw);
            $bean->setArg('error', 10001);
        } else {
            // 如何对所有数据进行和校验
            $data['time'] = time();
            $bean->setControllerClass(Device::class);
            $action_num = array_shift($data);
            // var_dump($data);
            switch ($action_num) {
                case 0x88:
                    $action = 'laser';
                    break;
                default:
                    $action = 'error';
            }
            $bean->setAction($action);
            $bean->setArg('data', $data);
        }

        return $bean;
    }

    public static function encode(string $raw, $client): ?string
    {
        return $raw."\n";
    }
}